package com.naizhuai.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.naizhuai.ui.BaseFragment;
import com.naizhuai.util.SharedPreferenceUtil;
import com.naizhuai.util.ToastCompat;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseLazyFragment extends BaseFragment {

	public View view;
	public Boolean Instance = false;
	/** Fragment当前状态是否可见 */
	protected boolean isVisible;
	private Unbinder unbinder;

	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        view = inflater.inflate(getLayoutResID(), container, false);
		unbinder = ButterKnife.bind(this, view);
        initView(view);
        Instance = true;
        return view;
    }

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (getUserVisibleHint()) {
			isVisible = true;
			onIsVisible();
		} else {
			isVisible = false;
			onIsNotVisible();
		}

	}

	protected abstract void onIsNotVisible();

	private void onIsVisible() {

		if (!Instance || !isVisible) {
			return;
		}
		new Handler().post(new Runnable() {
			@Override
			public void run() {
				lazyLoad();
			}
		});
	}

	protected abstract void lazyLoad();

	protected abstract int getLayoutResID();

	protected abstract void initView(View view);

	protected void longToast(String str){
		ToastCompat.showToast(getActivity(),str, Toast.LENGTH_LONG);
	}

	protected void shortToast(String str){
		ToastCompat.showToast(getActivity(),str,Toast.LENGTH_SHORT);
	}


	protected <T> T getShareValue(String keyword, @NonNull T t) {
		return SharedPreferenceUtil.getInstance(getActivity()).getValue(keyword, t);
	}

	protected <T> boolean setShareValue(String keyword, T t) {
		return SharedPreferenceUtil.getInstance(getActivity()).saveValue(keyword, t);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		unbinder.unbind();
	}

}
